﻿
Imports System.Threading

Public Module threads

#If PocketPC OrElse Smartphone Then
    Private finishInitial As Boolean
    Private threadPara As threadStart2
    Private mutex As Mutex = Nothing
    Public Delegate Sub ParameterizedThreadStart(ByVal obj As Object)

    Public Class threadStart2
        Public start As ParameterizedThreadStart
        Public para As Object
    End Class
#End If

    Public Function startThread(ByVal invoke As ThreadStart) As Thread
        Dim thread As Thread = Nothing
        thread = New Thread(invoke)
        thread.Start()
        Return thread
    End Function

#If PocketPC OrElse Smartphone Then
    Private Sub threadsub()
        assert(not finishInitial, "should not finishInitial before thread really caught the parameter.")
        Dim para As threadstart2 = Nothing 
        para = threadPara
        finishInitial = true
        assert(Not para Is Nothing, "cannot get valid parameter.")
        para.start(para.para)
    End Sub
#Else
#If RETIRED Then
    Private Sub threadsub(ByVal obj As Object)
        Dim para As threadStart2 = Nothing
        para = convertor.cast(Of threadStart2)(obj)
        assert(Not para Is Nothing, "cannot get valid parameter.")
        para.start(para.para)
    End Sub
#End If
#End If

    Public Function startThread(ByVal invoke As ParameterizedThreadStart, ByVal parameter As Object) As Thread
        Dim thread As Thread = Nothing
#If PocketPC OrElse Smartphone Then
        thread = New Thread(AddressOf threadsub)
        Dim para As threadStart2 = Nothing
        para = New threadStart2()
        para.start = invoke
        para.para = parameter
        assert(Mutex.WaitOne(), "cannot lock mutex when startThread.")
        threadPara = para
        thread.Start()
        While Not finishInitial
            sleep(64)
        End While
        Mutex.ReleaseMutex()
        'max qps on WindowsCE is 1000/defaultWaitTime, accroding to current setting, is about 64
#Else
        thread = New Thread(invoke)
        thread.Start(parameter)
        'seems no max qps limit on other platform
#End If

        Return thread
    End Function

#If PocketPC OrElse Smartphone Then
    Sub New()
        mutex = New Mutex()
    End Sub
#End If
End Module
